<template>
  <!-- 分配权限的弹层 -->
  <el-dialog title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)" :visible="showAssignDialog" @close="closeAssignDialog">
    <!-- 权限点数据展示 -->
    <!--node-key 选中时绑定的数据字段(唯一) -->
    <el-tree ref="tree" node-key="id" show-checkbox check-strictly default-expand-all :data="permList" :props="{label: 'name'}"></el-tree>

    <template #footer>
      <el-button @click="closeAssignDialog">取消</el-button>
      <el-button type="primary" @click="assignPerm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { transformTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    showAssignDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      permList: [],
      roleId: null
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 给角色分配权限
    async assignPerm () {
      try {
        await assignPerm({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
        this.$message.success('角色分配权限成功！')
        this.$emit('update:showAssignDialog', false)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取角色权限点回显
    async getRolePerm (id) {
      const { permIds } = await getRoleDetail(id)
      this.roleId = id
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    async getList () {
      const res = await getPermissionList()
      // console.table(res)
      // 数据转成树状结构
      this.permList = transformTreeData(res)
    },
    closeAssignDialog () {
      this.$emit('update:showAssignDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
